
<script setup>
import OrderInfo from './components/OrderInfo.vue'
import GoodsList from '@/components/goods/GoodsList.vue'
import { getInOutGoodsListApi, deleteInOutGoodsApi } from '@/apis/orderManagement.js'
import { ref } from 'vue'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'

const orderObj = ref({})

const params = ref({
  pageNum: 1,
  pageSize: 10,
  inorderid: "",
  outorderid: ""
})
const goodsList = ref([])
// 标记是否为首次加载页面
let isFirstLoad = true
const loadStatus = ref({
  status: "loadmore",
  noMore: false,
  loading: false
})
const type = ref('inorderdetail')
onLoad(async (options) => {
  type.value = options.type === 'inorder' ? 'inorderdetail' : 'outorderdetail'
  orderObj.value = JSON.parse(options.data)
  if (options.type === 'inorder') {
    params.value.inorderid = orderObj.value.id
  } else {
    params.value.outorderid = orderObj.value.id
  }
  await getGoodsList()
  isFirstLoad = false
})

onShow(async () => {
  if (isFirstLoad) return
  params.value.pageNum = 1
  loadStatus.value.noMore = false
  loadStatus.value.status = "loadmore"
  goodsList.value = []
  await getGoodsList()
})

onReachBottom(() => {
  if (!loadStatus.value.noMore) {
    getGoodsList()
  }
})

const getGoodsList = async () => {
  try {
    const res = await getInOutGoodsListApi(params.value, type.value)
    const { rows, total } = res
    if (total === 0) return
    if (params.value.pageNum === 1) {
      goodsList.value = rows
    } else {
      goodsList.value = [...goodsList.value, ...rows]
    }
    if (rows.length < params.value.pageSize || goodsList.value.length >= total) {
      loadStatus.value.noMore = true
      loadStatus.value.status = "nomore"
    } else {
      loadStatus.value.status = "loadmore"
    }
    params.value.pageNum++
  } catch (error) {
    loadStatus.value.status = "loadmore"
  } finally {
    loadStatus.value.loading = false
  }
}

// 删除货物
const handlerDelete = (item) => {
  console.log(item)
  uni.showModal({
    title: '温馨提示',
    content: `确定要删除${item.goodsname}的数据吗?`,
    success: async res => {
      if (!res.confirm) return
      await deleteInOutGoodsApi(item.id, type.value)
      goodsList.value = goodsList.value.filter(i => i.id !== item.id)
    }
  })
}

const handlerEdit = (item) => {
  uni.navigateTo({
    url: `/pages/orderManagement/goodsForm?inorderid=${orderObj.value.id}&id=${item.id}&type=${type.value}`
  })
}
</script>


<template>
  <view class="page_container">
    <u-sticky>
      <OrderInfo :order="orderObj" />
    </u-sticky>
    <GoodsList :goodsList="goodsList" :loadmoreStatus="loadStatus.status" :type="type" :isOrderPage="true"
      @clickDelete="handlerDelete" @clickEdit="handlerEdit" />
  </view>
</template>


<style scoped lang="scss"></style>
